package nio.nio.group;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

/**
 * @author 帅小伙
 * @date 2022/1/15
 * @description
 */
public class GroupChatClient {


    //定义相关属性
    private final String HOST = "127.0.0.1";
    private final int PORT = 6667;
    private Selector selector;
    private SocketChannel socketChannel;
    private String userName;


    // 完成初始化工作
    public GroupChatClient() {
        try {
            selector = Selector.open();
            socketChannel = socketChannel.open(new InetSocketAddress(HOST, PORT));
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_READ);
            userName = socketChannel.getLocalAddress().toString().substring(1);

            System.out.println(userName + "  is ok  ....");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void sendInfo(String info) {
        info = userName+"说:"+info;
        try{
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        }catch (IOException e) {
            e.printStackTrace();
        }
    }


    // 读取回复的消息
    public void readInfo(){
        try {
            int readChannels = selector.select();

            if(readChannels > 0){//有事件发生的通道
                Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();

                while(keyIterator.hasNext()){
                    SelectionKey key = keyIterator.next();
                    if(key.isReadable()){
                        //得到相关的通道
                        SocketChannel sc  = (SocketChannel)key.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        sc.read(buffer);
                        String msg = new String(buffer.array());
                        System.out.println(msg.trim());

                    }
                }
                // 删除当前的selectionKey  防止重复操作
                keyIterator.remove();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        GroupChatClient client = new GroupChatClient();

        // 启动一个线程
        new Thread(()->{
            while(true){
                client.readInfo();
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();


        //发送数据
        Scanner scanner = new Scanner(System.in);
        while(scanner.hasNextLine()){
            String info = scanner.nextLine();
            client.sendInfo(info);
        }

    }
}
